package com.example.crmweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.crmweb.controller.AuthController;
import com.example.crmweb.entity.Auth;
import com.example.crmweb.entity.Role;
import com.example.crmweb.entity.RoleAuth;
import com.example.crmweb.mapper.RoleAuthMapper;
import com.example.crmweb.service.RoleAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crmweb.lang.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author -CRM-
 * @since 2022-03-18
 */
@Service
public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthMapper, RoleAuth> implements RoleAuthService {

    @Resource
    private AuthServiceImpl authService;
    @Resource
    private RoleAuthMapper roleAuthMapper;


    /**
     * 查找角色的所有权限
     *
     * @param roleId
     * @return
     */
    @Override
    public Result batchDescribe(Integer roleId) {
//        先获取所有开启权限
        List<Auth> allAuth = authService.batchDescribe();
//        根据角色id查找所有权限id
        int[] authIds = roleAuthMapper.query(roleId);

        for (int i = 0; i < authIds.length; i++) {
            for (int j = 0; j < allAuth.size(); j++) {
                if (authIds[i] == allAuth.get(j).getId()) {
//                    如果grant属性为1，说明有这个权限
                    allAuth.get(j).setGrant(1);
                }
            }
        }
        return Result.success(200, "查询成功", allAuth);

    }

    /**
     * 更改某个角色的权限（添加，删除）
     *
     * @param role
     * @param authIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Result modifyAuth(Role role, Integer[] authIds) {

//        先获取角色id
        Integer roleId = role.getId();
//        根据角色id查询中间表中权限
        int[] auths = roleAuthMapper.query(roleId);
//        如果有权限，根据角色id删除中间表所有的权限
        if (auths != null) {
            roleAuthMapper.delete(roleId);
        }

//        添加所有的新的权限id
        batchInsert(roleId,authIds);
//        修改保存的同时，返回更改后的权限列表
        Result result = batchDescribe(roleId);
        return Result.success(200, "修改成功", result);
    }

    /**
     * 批量添加某个角色的权限
     * @param authIds
     */
    @Override
    public void batchInsert(Integer roleId,Integer[] authIds){


        for (int i = 0; i < authIds.length; i++) {
            RoleAuth roleAuth = new RoleAuth();
            roleAuth.setRoleId(roleId);
            roleAuth.setAuthId(authIds[i]);
            roleAuthMapper.insert(roleAuth);
        }
    }
}
